package com.xatz.scanner

import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.xatz.ksoap2_android.SoapEnvelope
import com.xatz.ksoap2_android.serialization.SoapObject
import com.xatz.ksoap2_android.serialization.SoapSerializationEnvelope
import com.xatz.ksoap2_android.transport.HttpTransportSE
import com.xatz.scanner.bean.CarBean
import com.xatz.scanner.bean.TargetLibraryBean
import com.xatz.scanner.bean.TargetStackBean
import com.xatz.scanner.databinding.ActivityWarehouseReceiptBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
import java.io.StringReader
import java.util.concurrent.Executors
import java.util.concurrent.ThreadPoolExecutor

/**
 * Created by tdq on 2022/1/10.
 *
 * 移库倒垛
 */
class WarehouseReceiptActivity : AppCompatActivity(), ScannerManger.OnScannerResultListener {

    private var mBinding: ActivityWarehouseReceiptBinding? = null

    private val mTargetLibraryBeans = mutableListOf<TargetLibraryBean>()

    private val mTargetStackBeans = mutableListOf<TargetStackBean>()

    private var mTargetLibraryStr = "请选择"

    private var mTargetStackStr = "请选择"

    private val mThread = Executors.newCachedThreadPool()

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityWarehouseReceiptBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
        ScannerManger.init(this)
        ScannerManger.setOnScannerResultListener(this)
        initView()
    }

    private fun initView() {
        mBinding?.btnClose?.setOnClickListener {
            transferFinish()
        }
        getTargetLibraryOnNet()
    }

    private fun transferFinish() {
        val barCode = mBinding?.etPartNum?.text?.trim().toString()
        if (mTargetLibraryStr == "请选择") {
            toast("请选择目标库")
            return
        }
        if (mTargetStackStr == "请选择") {
            toast("请选择目标垛")
            return
        }
        if (barCode.isBlank()) {
            toast("请扫描件次号")
            return
        }
        mThread.submit {
            val userAccount =
                getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                    .getString(Constant.userAccount, "").toString()
            val namespace = "http://tempuri.org/"
            val transUrl = "http://www.sxjbjt.com:9084/Service1.asmx"
            val method = "YiKuComplete"
            //注意版本使用，这个需要跟后台询问或者从wsdl文档或者服务说明中查看
            val envolopeVersion = SoapEnvelope.VER11
            //可能是namspace+method拼接
            val soapAction = "http://tempuri.org/YiKuComplete"
            val request = SoapObject(namespace, method)
            //参数一定注意要有序，尽管是addProperty（），不要当作HttpUrl可以使用LinkedHashMap封装
            request.addProperty("barcode", barCode)
            request.addProperty("userId", userAccount)
            request.addProperty("kf", mTargetLibraryStr)
            request.addProperty("dw", mTargetStackStr)
            // SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            val envelope = SoapSerializationEnvelope(envolopeVersion)
            envelope.setOutputSoapObject(request)
            envelope.dotNet = true
            val se = HttpTransportSE(transUrl)
            try {
                se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
                val response = envelope.bodyIn as SoapObject
                //response的处理需要根据返回的具体情况，基本都要进行下面一步
                Timber.e(response.toString())
                val responseSoapObject =
                    response.getProperty("SaleOutCompleteCommonResult") as SoapObject
                val resultCode = responseSoapObject.getProperty("resultCode").toString()
                val resultMsg = responseSoapObject.getProperty("resultMsg").toString()
                if (resultCode == "0") {
                    runOnUiThread {

                    }
                } else {

                }

            } catch (e: IOException) {
                e.printStackTrace()
            } catch (e: XmlPullParserException) {
                e.printStackTrace()
            }
        }
    }

    private fun getTargetStackOnNet() {
        mService.getDWInfo(mTargetLibraryStr).enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { parseTargetStackXMLWithPull(it) }
                    Timber.e(mTargetStackBeans.size.toString())
                    mTargetStackBeans.add(0, TargetStackBean("请选择", "", "", ""))
                    val mStackAdapter = ArrayAdapter(
                        this@WarehouseReceiptActivity,
                        R.layout.spinner_select_text,
                        R.id.tvCarNum,
                        mTargetStackBeans.map { it.C_DW })
                    mBinding?.spinTargetStack?.adapter = mStackAdapter
                    mBinding?.spinTargetStack?.onItemSelectedListener =
                        object : AdapterView.OnItemSelectedListener {
                            override fun onItemSelected(
                                parent: AdapterView<*>?,
                                view: View?,
                                position: Int,
                                id: Long
                            ) {
                                mTargetStackStr = mTargetStackBeans[position].C_DW
                                Timber.e(mTargetStackStr)
                            }

                            override fun onNothingSelected(parent: AdapterView<*>?) {
                            }
                        }
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Timber.e(t)
            }

        })
    }

    private fun getTargetLibraryOnNet() {
        mService.getKFInfo().enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { parseTargetLibraryXMLWithPull(it) }
                    mTargetLibraryBeans.add(0, TargetLibraryBean("请选择", "", ""))
                    val mLibraryAdapter = ArrayAdapter(
                        this@WarehouseReceiptActivity,
                        R.layout.spinner_select_text,
                        R.id.tvCarNum,
                        mTargetLibraryBeans.map { it.C_KFMS })
                    mBinding?.spinTargetLibrary?.run {
                        adapter = mLibraryAdapter
                        onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                            override fun onItemSelected(
                                parent: AdapterView<*>?,
                                view: View?,
                                position: Int,
                                id: Long
                            ) {
                                mTargetLibraryStr = mTargetLibraryBeans[position].C_KFMS
                                getTargetStackOnNet()
                            }

                            override fun onNothingSelected(parent: AdapterView<*>?) {
                            }
                        }
                    }
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Timber.e(t)
            }

        })
    }

    private fun parseTargetLibraryXMLWithPull(xmlData: String) {
        var targetLibraryBean: TargetLibraryBean? = null
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                targetLibraryBean = TargetLibraryBean("", "", "")
                            }
                            "C_KFMS" -> targetLibraryBean?.C_KFMS = xmlPullParser.nextText()
                            "C_CJR" -> targetLibraryBean?.C_CJR = xmlPullParser.nextText()
                            "C_CJSJ" -> targetLibraryBean?.C_CJSJ = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            targetLibraryBean?.let { mTargetLibraryBeans.add(it) }
                            targetLibraryBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun parseTargetStackXMLWithPull(xmlData: String) {
        mTargetStackBeans.clear()
        var targetStackBean: TargetStackBean? = null
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                targetStackBean = TargetStackBean("", "", "", "")
                            }
                            "C_DW" -> targetStackBean?.C_DW = xmlPullParser.nextText()
                            "C_KF" -> targetStackBean?.C_KF = xmlPullParser.nextText()
                            "C_CJR" -> targetStackBean?.C_CJR = xmlPullParser.nextText()
                            "C_CJSJ" -> targetStackBean?.C_CJSJ = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            targetStackBean?.let { mTargetStackBeans.add(it) }
                            targetStackBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onScannerResult(data: String?, labelType: String) {
        data?.run {
            if (this.startsWith("SO")) {
                getOldInfo(this)
            }
        }
    }

    private fun getOldInfo(soCode: String) {
        mService.getOldInfo(soCode).enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { parseTargetLibraryXMLWithPull(it) }
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Timber.e(t)
            }

        })
    }

    override fun onDestroy() {
        super.onDestroy()
        ScannerManger.onClosed()
    }

    override fun onResume() {
        super.onResume()
        // The application is in foreground
        if (ScannerManger.emdkManager != null) {
            // Acquire the barcode manager resources
            ScannerManger.initBarcodeManager(this)
        }
    }

    override fun onPause() {
        super.onPause()
        // The application is in background
        // Release the barcode manager resources
        ScannerManger.deInitScanner()
        ScannerManger.deInitBarcodeManager()
    }
}